﻿<% @Page Language="C#" %>
<html>
<head>
	<title>File upload in ASP.NET</title>
</head>
<body bgcolor="#ffffff" style="font:8pt verdana;">
<script language="C#" runat="server">
void btnUploadTheFile_Click(object Source, EventArgs evArgs) 
{
	string strFileNameOnServer = txtServername.Value;
    string strBaseLocation = "/upload/";
    string strDomain="";
    int loop1, loop2;
    NameValueCollection coll;

    // Load ServerVariable collection into NameValueCollection object.
    coll = Request.ServerVariables;
	//txtOutput.InnerHmtl=Response.Write(Request.ServerVariables("URL"));
    
	if ("" == strFileNameOnServer) 
	{
		txtOutput.InnerHtml = "Error - a file name must be specified.";
		return;
	}

	if (null != uplTheFile.PostedFile) 
	{
		try 
		{
            // Get names of all keys into a string array. 
            String[] arr1 = coll.AllKeys;
            for (loop1 = 0; loop1 < arr1.Length; loop1++)
            {
                // Response.Write("Key: " + arr1[loop1] + "<br>");
                if (arr1[loop1].CompareTo("HTTP_ORIGIN") == 0)
                {
                    String[] arr2 = coll.GetValues(arr1[loop1]);
                    for (loop2 = 0; loop2 < arr2.Length; loop2++)
                    {
                        //Response.Write("Value " + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");
                        strDomain = Server.HtmlEncode(arr2[loop2]);
                    }
                }
            }
			//uplTheFile.PostedFile.SaveAs(strDomain+strBaseLocation+strFileNameOnServer);
            uplTheFile.PostedFile.SaveAs(Server.MapPath(strBaseLocation)+strFileNameOnServer);
			txtOutput.InnerHtml = "File <b>" +
                strDomain + strBaseLocation + strFileNameOnServer + "</b> uploaded successfully ";
            
            
		}
		catch (Exception e) 
		{
			txtOutput.InnerHtml = "Error saving <b>" +
                strDomain + strBaseLocation + strFileNameOnServer + "</b><br>" + e.ToString();
		}
	}
}
</script>

<table>
<form id="Form1" enctype="multipart/form-data" runat="server">
<tr>
  <td>Select file:</td>
  <td><input id="uplTheFile" type=file runat="server"></td>
</tr>
<tr>
  <td>Name on server:</td>
  <td><input id="txtServername" type="text" runat="server"></td>
</tr>
<tr>
  <td colspan="2">
  <input type=button id="btnUploadTheFile" value="Upload" 
                    OnServerClick="btnUploadTheFile_Click" runat="server">
  </td>
</tr>
</form>
</table>
    
<span id=txtOutput style="font: 8pt verdana;" runat="server" />
</body>
</html>

